import axios from 'axios'
import { getToken, removeToken } from './auth' // 假设你有身份验证工具函数
import { apiPath, baseUrl, tenantId } from '@/utils/config';
import { UniAdapter } from 'uniapp-axios-adapter'

// 创建axios实例
const service = axios.create({
    baseURL: `${baseUrl}${apiPath}`, // 从环境变量获取基础API地址
    timeout: 10000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    adapter: UniAdapter
})

// 请求拦截器
service.interceptors.request.use(
    async (config) => {
        // 在发送请求之前做些什么
        const token = await getToken()
        if (token) {
            config.headers['Authorization'] =  token
        }

        // 如果是GET请求，添加时间戳防止缓存
        if (config.method === 'get') {
            config.params = {
                ...config.params,
                _t: new Date().getTime()
            }
        }

        // uni-app 环境下需要适配
        if (typeof uni !== 'undefined') {
            // 添加平台标识
            config.headers['X-Platform'] = 'uniapp'
        }

        config.headers['tenant-id'] = tenantId

        return config
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data

        // 根据后端约定判断请求状态
        if (res.code !== 200 && res.code !== 0) {
            // token过期或无效
            if (res.code === 401 || res.code === 10001) {
                removeToken()
                uni.showToast({
                    title: '登录已过期，请重新登录',
                    icon: 'none'
                })
                const paths = getCurrentPages()
                if(paths.length>1){
                    let curRoute = paths[paths.length - 1].route;
                    if(curRoute==='pages/login/login'){
                        return
                    }
                }
                setTimeout(() => {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                }, 1500)
            } else {
                uni.showToast({
                    title: res.msg || '请求错误',
                    icon: 'none'
                })
            }
            return Promise.reject(new Error(res.msg || 'Error'))
        } else {
            return res
        }
    },
    (error) => {
        // 对响应错误做点什么
        let message = '网络错误'

        if (error.response) {
            switch (error.response.status) {
                case 400:
                    message = '请求错误'
                    break
                case 401:
                    message = '未授权，请重新登录'
                    removeToken()
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    break
                case 403:
                    message = '拒绝访问'
                    break
                case 404:
                    message = '请求地址出错'
                    break
                case 408:
                    message = '请求超时'
                    break
                case 500:
                    message = '服务器内部错误'
                    break
                case 501:
                    message = '服务未实现'
                    break
                case 502:
                    message = '网关错误'
                    break
                case 503:
                    message = '服务不可用'
                    break
                case 504:
                    message = '网关超时'
                    break
                case 505:
                    message = 'HTTP版本不受支持'
                    break
                default:
                    message = '网络连接错误'
            }
        } else if (error.message.includes('timeout')) {
            message = '请求超时'
        } else if (error.message === 'Network Error') {
            message = '网络连接错误'
        }

        uni.showToast({
            title: message,
            icon: 'none'
        })

        return Promise.reject(error)
    }
)

// 封装通用请求方法
const request = (options) => {
    // 适配uni-app环境
    if (typeof uni !== 'undefined') {
        // 在这里可以添加uni-app特定的适配逻辑
    }

    return service(options)
}

// 封装GET请求
const get = (url, params, options = {}) => {
    return request({
        url,
        method: 'GET',
        params,
        ...options
    })
}

// 封装POST请求
const post = (url, data, options = {}) => {
    return request({
        url,
        method: 'POST',
        data,
        ...options
    })
}

// 封装PUT请求
const put = (url, data, options = {}) => {
    return request({
        url,
        method: 'PUT',
        data,
        ...options
    })
}

// 封装DELETE请求
const del = (url, params, options = {}) => {
    return request({
        url,
        method: 'DELETE',
        params,
        ...options
    })
}

// 封装上传文件方法
const upload = (url, filePath, formData = {}, options = {}) => {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: process.env.VUE_APP_BASE_API + url,
            filePath,
            name: 'file',
            formData,
            header: {
                'Authorization': 'Bearer ' + getToken()
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    const data = JSON.parse(res.data)
                    resolve(data)
                } else {
                    reject(new Error('上传失败'))
                }
            },
            fail: (error) => {
                reject(error)
            }
        })
    })
}

// 封装下载文件方法
const download = (url, options = {}) => {
    return new Promise((resolve, reject) => {
        uni.downloadFile({
            url: process.env.VUE_APP_BASE_API + url,
            header: {
                'Authorization': 'Bearer ' + getToken()
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    resolve(res.tempFilePath)
                } else {
                    reject(new Error('下载失败'))
                }
            },
            fail: (error) => {
                reject(error)
            }
        })
    })
}

export default {
    request,
    get,
    post,
    put,
    delete: del,
    upload,
    download
}